﻿Imports LinhKienMayTinh.CommonMethods

Public Class NewsEdit
    Inherits BasePage

    Protected dsSource As DataSet

    Protected Const VIEW_MODE As String = "VIEW_MODE"
    Private Const NEWS_CODE As String = "NEWS_CODE"

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim newsCode As Integer
        Try
            If Not IsPostBack Then

                '' nếu có querystring thì là mode update, ngược lại thì là mode tạo mới
                If IsNothing(Request.QueryString("CODE")) Then
                    ViewState(VIEW_MODE) = 1
                Else
                    ViewState(VIEW_MODE) = 0
                    newsCode = CInt(Request.QueryString("CODE"))
                    ViewState(NEWS_CODE) = newsCode
                End If

                If ViewState(VIEW_MODE) = 1 Then
                    Call ChangeFormMode(ViewState(VIEW_MODE))
                Else
                    Call SetFormData()
                End If

            End If
        Catch ex As Exception
            Server.Transfer("~/Pages/Error.aspx")
        End Try
    End Sub

    Private Sub NewsEdit_Init(sender As Object, e As System.EventArgs) Handles Me.Init
        Dim master As AdminMasterPage = DirectCast(Me.Page.Master, AdminMasterPage)
        ''add link css
        master.CssLinkAdd(ResolveUrl("~/Style/NewsEdit.css"))
        ''add script tool quan ly file
        master.ScriptLinkAdd(ResolveUrl("~/ckfinder/ckfinder.js"))
        master.ScriptLinkAdd(ResolveUrl("~/Scripts/NewsEdit.js"))
    End Sub

    ''' <summary>
    ''' FucntionExec
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Protected Overridable Sub FucntionExec(ByVal sender As Object, ByVal e As System.EventArgs) _
                                                Handles btnEdit.Click,
                                                        btnSave.Click,
                                                        btnDelete.Click,
                                                        btnCancel.Click,
                                                        btnAdd.Click,
                                                        btnRestore.Click

        Dim control As Button = DirectCast(sender, Button)

        Try
            Select Case control.ID
                Case btnEdit.ID     '' button edit
                    ViewState(VIEW_MODE) = 2
                    Call SetFormData()
                Case btnSave.ID     '' button save
                    Call UpdateData()
                Case btnDelete.ID   '' button delete
                    Call DeleteData()
                Case btnCancel.ID   '' button cancel
                    If ViewState(VIEW_MODE) = 1 Then
                        Call ClearError()
                        Call ClearControl()
                    Else
                        ViewState(VIEW_MODE) = 0
                        Call SetFormData()
                    End If
                Case btnAdd.ID      '' button tạo mới
                    Response.Redirect("~/Admin/NewsEdit.aspx")

                Case btnRestore.ID  '' button khôi phục
                    Call RestoreData()

            End Select

        Catch ex As Exception
            Throw
        End Try

    End Sub

#Region "Khai báo các function method"

    ''' <summary>
    ''' UpdateData
    ''' </summary>
    ''' <remarks></remarks>
    Protected Overridable Sub UpdateData()
        Dim xSql As String
        Dim da As DBAccess
        Dim ds As DataSet

        Try
            da = GetDBAccess()

            '' nếu có lỗi input thì không làm gì cả.
            If CheckFormError() = False Then
                Exit Sub
            End If
            '' get cau sql
            If ViewState(VIEW_MODE) = 1 Then
                xSql = CreateInsertSql()
                ds = da.GetDBDataset(xSql)
                ViewState(NEWS_CODE) = Nz(ds.Tables(0).Rows(0)("ID"), 0)
            Else
                xSql = CreateUpdateSql()
                da.ExecuteSqlString(xSql)
            End If

            '' sau khi update data thì trở về mode tham chiếu
            ViewState(VIEW_MODE) = 0
            Call SetFormData()

            Response.Write(String.Format("<script type='text/javascript'>alert('Tin tức đã được save thành công.');window.location = '{0}';</script>", Request.RawUrl))
        Catch ex As Exception
            Response.Write("<script type='text/javascript'>alert('Đã xảy ra lỗi trong quá trình lưu tin tức. Xin hãy thử lại!');</script>")
        End Try

    End Sub

    ''' <summary>
    ''' delete tin tức
    ''' </summary>
    ''' <remarks></remarks>
    Protected Overridable Sub DeleteData()
        Dim xSql As String
        Dim da As DBAccess

        Try
            da = GetDBAccess()

            xSql = CreateDeleteSql()

            da.ExecuteSqlString(xSql)

            ViewState(VIEW_MODE) = 0
            Call SetFormData()

            Response.Write("<script type='text/javascript'>alert('Đã delete tin tức thành công.');</script>")
        Catch ex As Exception
            Response.Write("<script type='text/javascript'>alert('Đã có lỗi khi delete tin tức. Xin hãy thử lại!');</script>")
        End Try


    End Sub

    ''' <summary>
    ''' khôi phục tin tức đã delete
    ''' </summary>
    ''' <remarks></remarks>
    Protected Overridable Sub RestoreData()
        Dim da As DBAccess
        Dim nCode As Integer
        Dim xSql As String

        Try
            da = GetDBAccess()

            nCode = CInt(ViewState(NEWS_CODE))
            xSql = "UPDATE T_NEWS SET DEL_FLG = 0 WHERE CODE = " & ToSqlStr(nCode, SqlDataType.DataType_Integer)

            da.ExecuteSqlString(xSql)

            ViewState(VIEW_MODE) = 0
            Call SetFormData()

        Catch ex As Exception

        End Try

    End Sub

    Private Function GetNewsByCode(ByVal pCode As Integer) As DataSet

        Dim xSql As String
        Dim ds As DataSet
        Dim dataAccess As DBAccess

        Try
            dataAccess = Me.GetDBAccess()

            xSql = ""
            xSql = xSql & vbCrLf & "SELECT"
            xSql = xSql & vbCrLf & "		T_NEWS.CODE,"
            xSql = xSql & vbCrLf & "		T_NEWS.NAME        AS TITLE,"
            xSql = xSql & vbCrLf & "		T_NEWS.LINK_NAME,"
            xSql = xSql & vbCrLf & "		T_NEWS.IMG_LINK,"
            xSql = xSql & vbCrLf & "		T_NEWS.SUMMARY,"
            xSql = xSql & vbCrLf & "		T_NEWS.CONTENT,"
            xSql = xSql & vbCrLf & "		T_NEWS.TAG,"
            xSql = xSql & vbCrLf & "		T_NEWS.DEL_FLG,"
            xSql = xSql & vbCrLf & "		T_NEWS.AD_DATE,"
            xSql = xSql & vbCrLf & "		T_NEWS.UD_DATE"
            xSql = xSql & vbCrLf & "FROM "
            xSql = xSql & vbCrLf & "        T_NEWS"
            xSql = xSql & vbCrLf & "WHERE"
            xSql = xSql & vbCrLf & "        T_NEWS.CODE    = @CODE"

            xSql = Replace(xSql, "@CODE", ToSqlStr(pCode, SqlDataType.DataType_Integer))

            ds = dataAccess.GetDBDataset(xSql)

            Return ds
        Catch ex As Exception
            Throw ex
        End Try
    End Function

    ''' <summary>
    ''' set data cho form
    ''' </summary>
    ''' <remarks></remarks>
    Protected Overridable Sub SetFormData()

        Dim dsNews As DataSet
        Dim nCode As Integer

        Try
            '' clear tất cả các control
            Call ClearControl()
            Call ClearError()

            '' get data
            nCode = CInt(ViewState(NEWS_CODE))
            dsNews = GetNewsByCode(nCode)

            '' nếu data không tồn tại thì thay đổi mode thành tạo mới
            If IsNothing(dsNews) = True Then
                ViewState(VIEW_MODE) = 1
                Call ChangeFormMode(ViewState(VIEW_MODE))
                Exit Sub
            End If

            '' set data cho các control
            With dsNews.Tables(0).Rows(0)
                '' CODE
                ViewState(NEWS_CODE) = fToInt(.Item("CODE"))
                txtCode.Text = fToText(.Item("CODE"))

                '' TITLE
                txtTitle.Text = fToText(.Item("TITLE"))

                '' Image link
                txtFilePath.Text = fToText(.Item("IMG_LINK"))

                '' nếu là mode tham chiếu thì set cho các control literal
                If ViewState(VIEW_MODE) = 0 Then
                    ltSummary.Text = fToText(.Item("SUMMARY"))
                    ltContent.Text = fToText(.Item("CONTENT"))
                Else '' ngược lại thì set cho các control html editor
                    txtSummary.Text = fToText(.Item("SUMMARY"))
                    txtContent.Text = fToText(.Item("CONTENT"))
                End If

                '' TAG
                txtTag.Text = fToText(.Item("TAG"))

                '' trạng thái delete
                lbDel.Text = IIf(CInt(.Item("DEL_FLG")) = 0, "", "Đã delete")
            End With

            '' thay đổi form mode
            Call ChangeFormMode(ViewState(VIEW_MODE))
        Catch ex As Exception
            Throw
        End Try

    End Sub

    ''' <summary>
    ''' ChangeFormMode
    ''' </summary>
    ''' <param name="pMode"></param>
    ''' <remarks></remarks>
    Protected Overridable Sub ChangeFormMode(pMode As Integer)

        Select Case pMode
            Case 0      '' mode tham chiếu
                txtTitle.Enabled = False
                txtTag.Enabled = False
                txtFilePath.Enabled = False
                btnBrowse.Enabled = False
                btnEdit.Enabled = True
                btnSave.Enabled = False
                btnCancel.Enabled = False
                btnDelete.Enabled = True
                btnAdd.Enabled = True
            Case 1      '' mode tạo mới
                txtTitle.Enabled = True
                txtTag.Enabled = True
                txtFilePath.Enabled = True
                btnBrowse.Enabled = True
                btnEdit.Enabled = False
                btnSave.Enabled = True
                btnCancel.Enabled = True
                btnDelete.Enabled = False
                btnAdd.Enabled = False
            Case 2      '' mode update      
                txtTitle.Enabled = True
                txtTag.Enabled = True
                txtFilePath.Enabled = True
                btnBrowse.Enabled = True
                btnEdit.Enabled = False
                btnSave.Enabled = True
                btnCancel.Enabled = True
                btnDelete.Enabled = True
                btnAdd.Enabled = False
        End Select

        If lbDel.Text.Length = 0 Then
            btnRestore.Visible = False
            If ViewState(VIEW_MODE) <> 1 Then
                btnDelete.Enabled = True
            End If
        Else
            btnRestore.Visible = True
            btnDelete.Enabled = False
        End If
    End Sub

    ''' <summary>
    ''' check lỗi
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Protected Overridable Function CheckFormError() As Boolean

        Dim bNoError As Boolean = True

        Call ClearError()

        If txtTitle.Text.Length < 1 Then
            lbErrorTitle.Text = "*Tựa đề không được phép rỗng."
            bNoError = False
        End If

        Return bNoError

    End Function

    ''' <summary>
    ''' clear error message
    ''' </summary>
    ''' <remarks></remarks>
    Protected Overridable Sub ClearError()

        lbErrorTitle.Text = String.Empty

    End Sub

    ''' <summary>
    ''' ClearControl
    ''' </summary>
    ''' <remarks></remarks>
    Protected Overridable Sub ClearControl()

        txtCode.Text = String.Empty
        txtTitle.Text = String.Empty
        txtFilePath.Text = String.Empty
        txtSummary.Text = String.Empty
        txtContent.Text = String.Empty
        txtTag.Text = String.Empty

    End Sub

    ''' <summary>
    ''' tạo câu sql Insert
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Protected Overridable Function CreateInsertSql() As String
        Dim xSql As String
        Dim xTitle As String
        Dim xLinkName As String

        Try
            xTitle = txtTitle.Text.Trim()
            xLinkName = TrimAccentedString(xTitle)
            xLinkName = TrimNonAlphaNumeric(xLinkName)
            xLinkName = TrimMultiWhiteSpace(xLinkName)
            xLinkName = xLinkName.Trim().ToLower()
            xLinkName = Replace(xLinkName, " ", "-")

            xSql = "BEGIN"
            xSql = xSql & vbCrLf & "INSERT INTO T_NEWS("
            xSql = xSql & vbCrLf & "NAME"
            xSql = xSql & vbCrLf & ",LINK_NAME"
            xSql = xSql & vbCrLf & ",IMG_LINK"
            xSql = xSql & vbCrLf & ",SUMMARY"
            xSql = xSql & vbCrLf & ",CONTENT"
            xSql = xSql & vbCrLf & ",TAG"
            xSql = xSql & vbCrLf & ",DEL_FLG"
            xSql = xSql & vbCrLf & ",AD_DATE"
            xSql = xSql & vbCrLf & ",UD_DATE"
            xSql = xSql & vbCrLf & ") VALUES("

            '' NAME
            xSql = xSql & vbCrLf & ToSqlStr(xTitle, SqlDataType.DataType_String)

            '' LINK_NAME
            xSql = xSql & vbCrLf & "," & ToSqlStr(xLinkName, SqlDataType.DataType_String)

            '' IMG_LINK
            xSql = xSql & vbCrLf & "," & ToSqlStr(txtFilePath.Text, SqlDataType.DataType_String)

            '' Summary
            xSql = xSql & vbCrLf & "," & ToSqlStr(txtSummary.Text, SqlDataType.DataType_String)

            '' Content
            xSql = xSql & vbCrLf & "," & ToSqlStr(txtContent.Text, SqlDataType.DataType_String)

            '' Tag
            xSql = xSql & vbCrLf & "," & ToSqlStr(txtTag.Text, SqlDataType.DataType_String)

            '' Del_flg
            xSql = xSql & vbCrLf & "," & ToSqlStr(0, SqlDataType.DataType_Integer)

            '' Ad_date
            xSql = xSql & vbCrLf & "," & ToSqlStr(Date.Now, SqlDataType.DataType_String)

            '' Ud_date
            xSql = xSql & vbCrLf & "," & ToSqlStr(Date.Now, SqlDataType.DataType_String)

            xSql = xSql & vbCrLf & ");"

            xSql = xSql & vbCrLf & "SELECT SCOPE_IDENTITY() AS ID;"

            xSql = xSql & vbCrLf & "END"

            Return xSql

        Catch ex As Exception
            Throw
        End Try

    End Function

    ''' <summary>
    ''' CreateUpdateSql
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Protected Overridable Function CreateUpdateSql() As String
        Dim xSql As String
        Dim xTitle As String
        Dim xLinkName As String

        Try
            xTitle = txtTitle.Text.Trim()
            xLinkName = TrimAccentedString(xTitle)
            xLinkName = TrimNonAlphaNumeric(xLinkName)
            xLinkName = TrimMultiWhiteSpace(xLinkName)
            xLinkName = xLinkName.Trim().ToLower()
            xLinkName = Replace(xLinkName, " ", "-")

            xSql = "UPDATE T_NEWS SET"
            xSql = xSql & vbCrLf & "NAME = " & ToSqlStr(xTitle, SqlDataType.DataType_String)
            xSql = xSql & vbCrLf & ",LINK_NAME = " & ToSqlStr(xLinkName, SqlDataType.DataType_String)
            xSql = xSql & vbCrLf & ",IMG_LINK = " & ToSqlStr(txtFilePath.Text, SqlDataType.DataType_String)
            xSql = xSql & vbCrLf & ",SUMMARY = " & ToSqlStr(txtSummary.Text, SqlDataType.DataType_String)
            xSql = xSql & vbCrLf & ",CONTENT = " & ToSqlStr(txtContent.Text, SqlDataType.DataType_String)
            xSql = xSql & vbCrLf & ",TAG = " & ToSqlStr(txtTag.Text, SqlDataType.DataType_String)
            xSql = xSql & vbCrLf & ",UD_DATE = " & ToSqlStr(Date.Now, SqlDataType.DataType_String)
            xSql = xSql & vbCrLf & "WHERE"
            xSql = xSql & vbCrLf & "CODE = " & ToSqlStr(ViewState(NEWS_CODE), SqlDataType.DataType_Integer)

            Return xSql
        Catch ex As Exception
            Throw
        End Try

    End Function

    ''' <summary>
    ''' CreateDeleteSql
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Protected Overridable Function CreateDeleteSql() As String
        Dim xSql As String

        Try
            xSql = "UPDATE T_NEWS SET DEL_FLG = 1 WHERE CODE = " & ToSqlStr(ViewState(NEWS_CODE), SqlDataType.DataType_Integer)

            Return xSql
        Catch ex As Exception
            Throw
        End Try

    End Function

#End Region

End Class